/*
	Copyright (C) 2011 Daniel C. Dennison (dandennison84@gmail.com).  All rights reserved.
	This file is licensed under the EPL 1.0 (Eclipse Public License 1.0)
	A copy of the license can be found at http://www.eclipse.org/legal/epl-v10.html
*/

package com.gmail.dandennison84.accounting

class StatementBuilder extends NodeBuilder {
	private final List<Account> coa
	final Map<String, List<Account>> accounts = [:]

	StatementBuilder(List<Account> coa) {
		this.coa = coa
	}

	@Override
	protected void nodeCompleted(Object parent, Object node) {
		AccountType accountType = node.attribute('accountType')
		BalanceType balanceType = node.attribute('balanceType')
		ClosingType closingType = node.attribute('closingType')
		CashFlowStatementType cashFlowStatementType = node.attribute('cashFlowStatementType')
		String groupName = node.attribute('accountGroup')
		if(groupName || accountType || balanceType || closingType || cashFlowStatementType) {
			List<Account> a = accounts.get(node.name())
			if(!a) {
				a = []
				accounts.put(node.name(), a)
			}
			if(groupName) {
				a.addAll(coa.findAll {it.groupName == groupName})
			} else if(accountType) {
				a.addAll(coa.findAll {it.accountType == accountType})
			} else if(balanceType) {
				a.addAll(coa.findAll {it.balanceType == balanceType})
			} else if(closingType) {
				a.addAll(coa.findAll {it.closingType == closingType})
			} else {
				a.addAll(coa.findAll {it.cashFlowStatementType == cashFlowStatementType})
			}
		} else if (node.name() == 'account') {
			List<Account> a = accounts.get(parent.name())
			if(!a) {
				a = []
				accounts.put(parent.name(), a)
			}
			a << coa.find {it.name == node.value()}
		}
	}
}
